<template>
  <div class="order-detail">
    <!-- 订单状态卡片 -->
    <el-card class="status-card">
      <div class="status-header">
        <div class="status-info">
          <el-tag :type="getStatusType(orderInfo.status)" size="large">
            {{ getStatusText(orderInfo.status) }}
          </el-tag>
          <span class="status-desc">{{ getStatusDesc(orderInfo.status) }}</span>
        </div>
        <div class="order-actions">
          <el-button
            v-if="orderInfo.status === '0'"
            type="primary"
            @click="handlePay"
          >立即付款</el-button>
          <el-button
            v-if="orderInfo.status === '2'"
            type="success"
            @click="handleConfirm"
          >确认收货</el-button>
          <el-button
            v-if="orderInfo.status === '0'"
            type="danger"
            @click="handleCancel"
          >取消订单</el-button>
          <el-button
            v-if="orderInfo.status === '3'"
            type="primary"
            @click="handleComment"
          >评价</el-button>
        </div>
      </div>
      <el-steps :active="getStatusStep(orderInfo.status)" finish-status="success" class="status-steps">
        <el-step title="提交订单" description="已提交订单" />
        <el-step title="付款成功" :description="orderInfo.payTime || '待付款'" />
        <el-step title="商品发货" :description="orderInfo.deliveryTime || '待发货'" />
        <el-step title="交易完成" :description="orderInfo.finishTime || '待收货'" />
      </el-steps>
    </el-card>

    <!-- 订单信息卡片 -->
    <el-card class="info-card">
      <template #header>
        <div class="card-header">
          <span>订单信息</span>
        </div>
      </template>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单编号">{{ orderInfo.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ parseTime(orderInfo.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="付款时间">{{ orderInfo.payTime ? parseTime(orderInfo.payTime) : '-' }}</el-descriptions-item>
        <el-descriptions-item label="发货时间">{{ orderInfo.deliveryTime ? parseTime(orderInfo.deliveryTime) : '-' }}</el-descriptions-item>
        <el-descriptions-item label="完成时间">{{ orderInfo.finishTime ? parseTime(orderInfo.finishTime) : '-' }}</el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ getPaymentMethod(orderInfo.paymentMethod) }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 收货信息卡片 -->
    <el-card class="address-card">
      <template #header>
        <div class="card-header">
          <span>收货信息</span>
        </div>
      </template>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="收货人">{{ orderInfo.receiverName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ orderInfo.receiverPhone }}</el-descriptions-item>
        <el-descriptions-item label="收货地址">{{ orderInfo.receiverAddress }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ orderInfo.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 商品信息卡片 -->
    <el-card class="products-card">
      <template #header>
        <div class="card-header">
          <span>商品信息</span>
        </div>
      </template>
      <div class="products-list">
        <div v-for="product in orderInfo.products" :key="product.productId" class="product-item">
          <el-image 
            :src="baseUrl + product.image" 
            :preview-src-list="[baseUrl + product.image]" 
            class="product-image" 
          />
          <div class="product-info">
            <h4>{{ product.productName }}</h4>
            <p class="price">¥{{ product.price }}</p>
            <p class="quantity">x{{ product.quantity }}</p>
          </div>
          <div class="product-total">
            <p class="subtotal">小计：¥{{ (product.price * product.quantity).toFixed(2) }}</p>
          </div>
        </div>
      </div>
      <div class="order-total">
        <div class="total-item">
          <span>商品总数：</span>
          <span>{{ getTotalQuantity(orderInfo.products) }}件</span>
        </div>
        <div class="total-item">
          <span>商品总价：</span>
          <span>¥{{ getTotalAmount(orderInfo.products) }}</span>
        </div>
        <div class="total-item">
          <span>运费：</span>
          <span>¥{{ orderInfo.freight || '0.00' }}</span>
        </div>
        <div class="total-item amount">
          <span>实付金额：</span>
          <span class="price">¥{{ getOrderTotal(orderInfo) }}</span>
        </div>
      </div>
    </el-card>

    <!-- 支付确认对话框 -->
    <el-dialog
      title="确认支付"
      v-model="payDialogVisible"
      width="30%"
    >
      <div class="pay-dialog-content">
        <p>订单金额：<span class="amount">¥{{ orderInfo.totalAmount }}</span></p>
        <p class="tip">这是一个模拟支付流程，点击确认后将直接完成支付</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="payDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmPay" :loading="payLoading">
            确认支付
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrder, cancelOrder, confirmOrder, payOrder } from '@/api/user/order'
import { parseTime } from '@/utils/ruoyi'

const route = useRoute()
const router = useRouter()
const orderInfo = ref({})
const payDialogVisible = ref(false)
const payLoading = ref(false)
const baseUrl = import.meta.env.VITE_APP_BASE_API

// 获取订单详情
const getOrderInfo = async () => {
  if (!route.params.id) {
    ElMessage.error('订单ID不存在')
    return
  }
  try {
    const res = await getOrder(route.params.id)
    if (res.code === 200) {
      orderInfo.value = res.data
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  }
}

// 获取订单状态类型
const getStatusType = (status) => {
  const statusMap = {
    '0': 'warning',
    '1': 'primary',
    '2': 'success',
    '3': 'info',
    '4': 'danger'
  }
  return statusMap[status]
}

// 获取订单状态文本
const getStatusText = (status) => {
  const statusMap = {
    '0': '待付款',
    '1': '待发货',
    '2': '待收货',
    '3': '已完成',
    '4': '已取消'
  }
  return statusMap[status]
}

// 获取订单状态描述
const getStatusDesc = (status) => {
  const statusMap = {
    '0': '请尽快完成付款',
    '1': '商家正在处理您的订单',
    '2': '商品已发货，请注意查收',
    '3': '交易已完成',
    '4': '订单已取消'
  }
  return statusMap[status]
}

// 获取订单状态步骤
const getStatusStep = (status) => {
  const stepMap = {
    '0': 1,
    '1': 2,
    '2': 3,
    '3': 4,
    '4': 0
  }
  return stepMap[status]
}

// 获取支付方式文本
const getPaymentMethod = (method) => {
  const methodMap = {
    '1': '支付宝',
    '2': '微信支付',
    '3': '银行卡'
  }
  return methodMap[method] || '-'
}

// 计算商品总数量
const getTotalQuantity = (products) => {
  if (!products) return 0
  return products.reduce((total, product) => total + product.quantity, 0)
}

// 计算商品总金额
const getTotalAmount = (products) => {
  if (!products) return '0.00'
  return products.reduce((total, product) => total + product.price * product.quantity, 0).toFixed(2)
}

// 计算订单总金额
const getOrderTotal = (order) => {
  if (!order.products) return '0.00'
  const productsTotal = parseFloat(getTotalAmount(order.products))
  const freight = parseFloat(order.freight || 0)
  return (productsTotal + freight).toFixed(2)
}

// 立即付款
const handlePay = () => {
  payDialogVisible.value = true
}

// 确认支付
const confirmPay = async () => {
  payLoading.value = true
  try {
    const res = await payOrder(orderInfo.value.orderId)
    if (res.code === 200) {
      ElMessage.success('支付成功')
      payDialogVisible.value = false
      getOrderInfo()
    }
  } catch (error) {
    console.error('支付失败:', error)
    ElMessage.error('支付失败')
  } finally {
    payLoading.value = false
  }
}

// 确认收货
const handleConfirm = () => {
  ElMessageBox.confirm('确认要收货吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await confirmOrder(orderInfo.value.orderId)
      if (res.code === 200) {
        ElMessage.success('确认收货成功')
        getOrderInfo()
      }
    } catch (error) {
      console.error('确认收货失败:', error)
      ElMessage.error('确认收货失败')
    }
  })
}

// 取消订单
const handleCancel = () => {
  ElMessageBox.confirm('确认要取消订单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await cancelOrder(orderInfo.value.orderId)
      if (res.code === 200) {
        ElMessage.success('取消订单成功')
        getOrderInfo()
      }
    } catch (error) {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  })
}

// 评价订单
const handleComment = () => {
  router.push(`/user/comment/${orderInfo.value.orderId}`)
}

onMounted(() => {
  getOrderInfo()
})
</script>

<style lang="scss" scoped>
.order-detail {
  padding: 20px;

  .status-card {
    margin-bottom: 20px;

    .status-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30px;

      .status-info {
        display: flex;
        align-items: center;
        gap: 15px;

        .status-desc {
          color: #666;
          font-size: 14px;
        }
      }

      .order-actions {
        .el-button {
          margin-left: 10px;
        }
      }
    }

    .status-steps {
      padding: 20px 0;
    }
  }

  .info-card,
  .address-card,
  .products-card {
    margin-bottom: 20px;

    .card-header {
      font-weight: bold;
    }
  }

  .products-list {
    .product-item {
      display: flex;
      align-items: center;
      padding: 20px;
      border-bottom: 1px solid #eee;

      &:last-child {
        border-bottom: none;
      }

      .product-image {
        width: 80px;
        height: 80px;
        object-fit: cover;
        margin-right: 20px;
      }

      .product-info {
        flex: 1;

        h4 {
          margin: 0 0 10px;
          font-size: 16px;
        }

        .price {
          color: #f56c6c;
          font-weight: bold;
          margin: 5px 0;
        }

        .quantity {
          color: #666;
        }
      }

      .product-total {
        .subtotal {
          font-weight: bold;
          color: #f56c6c;
        }
      }
    }
  }

  .order-total {
    padding: 20px;
    border-top: 1px solid #eee;
    text-align: right;

    .total-item {
      margin-bottom: 10px;
      font-size: 14px;

      &.amount {
        font-size: 18px;
        font-weight: bold;

        .price {
          color: #f56c6c;
        }
      }
    }
  }
}

.pay-dialog-content {
  text-align: center;
  
  .amount {
    color: #f56c6c;
    font-size: 24px;
    font-weight: bold;
  }

  .tip {
    color: #909399;
    margin-top: 10px;
    font-size: 14px;
  }
}
</style> 